/*
 * @Date: 2023-03-26 14:19:11
 * @LastEditors: Zireael 1193875164@qq.com
 * @LastEditTime: 2023-03-26 14:55:31
 * @FilePath: \A19\backend\src\api\AMessages\Live\ApiTalkRequest.ts
 */
import { ApiCall, WsConnection } from "tsrpc";
import { ReqTalkRequest, ResTalkRequest } from "../../../shared/protocols/AMessages/Live/PtlTalkRequest";
import { Live } from '../../../utils/Classes/Live';
import { ServiceProto } from 'tsrpc-proto';
import { ServiceType } from '../../../shared/protocols/serviceProto';
import { ObjectId } from "mongodb";
import { Wsserver } from "../../..";

export default async function (call: ApiCall<ReqTalkRequest, ResTalkRequest>) {
    // TODO
    const user = call.currentUser
    const live = Live.lives.find(live => live.courseId.equals(call.req.course))
    if(!live) return call.error('不存在');
    
    
    if(user.role === 'teacher'){
        if(!call.req.stu) return call.error('不存在');
        const student = live.students.find(s => s._id.equals(call.req.stu as ObjectId))
        if(!student) return call.error('不存在');

        const p1 = student.connection?.sendMsg('AMessages/Live/TalkRequest',{
            studentName:user.name,
            studentId:user._id
        })

        //all numbers
        const connections = new Array<WsConnection>()
        live.students.forEach(s =>{
            if(s.connection){
                connections.push(s.connection)
            }
        })
        connections.push(live.host.connection)
        const p2 = Wsserver.broadcastMsg('AMessages/Live/SBTalk',{
            studentId:student._id,
            studentName:student.name
        },connections)

        await Promise.all([p1,p2])
        call.succ({
    
        })
    }
    else{
        await (live.host.connection as WsConnection<ServiceType>).sendMsg('AMessages/Live/TalkRequest',{
            studentName:user.name,
            studentId:user._id
        })
    
        call.succ({
    
        })
    }
}